package models

import (
	"chinasoccer/pkg/gredis"
	"chinasoccer/pkg/setting"
	"fmt"
	"log"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var db *gorm.DB
var cacher *gredis.Cacher

type Model struct {
	CreatedOn  int `json:"created_on" column:"created_on" `
	ModifiedOn int `json:"modified_on" column:"modified_on"`
	DeletedOn  int `json:"deleted_on"  column:"deleted_on"`
}

func Setup() {
	var err error
	dsn := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
		setting.DatabaseSetting.User,
		setting.DatabaseSetting.Password,
		setting.DatabaseSetting.Name,
		setting.DatabaseSetting.Host,
		setting.DatabaseSetting.Port,
	)

	db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})

	if err != nil {
		log.Fatalf("models.Setup err: %v", err)
	}
	// db.AutoMigrate(&User{})
	db.AutoMigrate(&Menu{})
	db.AutoMigrate(&Worker{})
	db.AutoMigrate(&Supplier{})
	db.AutoMigrate(&Good{})
	db.AutoMigrate(&PurchaseMasterTable{})
	db.AutoMigrate(&Power{})
	db.AutoMigrate(&PurchaseDetail{})

	cacher, err = gredis.New(gredis.Options{})

	if err != nil {
		log.Fatalf("redis.Setup err: %v", err)
	}
}

func GetDB() *gorm.DB {
	return db
}
